import React, { PropsWithChildren, useEffect, useState } from "react";
import { connect } from "react-redux";
import { CombinedState } from "../../store/reducers";
import { ProFileState } from "../../store/reducers/profile";
import actions from "../../store/actions/profile";
import LOGIN_TYPES from "../../typings/login-types";
import { RouteComponentProps } from "react-router";
import { Descriptions, Button, Alert, message, Upload } from "antd";
import NavHeader from "../../components/NavHeader";
import { AxiosError } from "axios";
import "./index.less";
import { LoadingOutlined, UploadOutlined } from "@ant-design/icons";
//当前的组件有三个属性来源
//1.mapStateToProps的返回值 2.actions对象类型 3. 来自路由 4.用户传入进来的其它属性
type StateProps = ReturnType<typeof mapStateToProps>;
type DispatchProps = typeof actions;
interface Params { };
type RouteProps = RouteComponentProps<Params>;
type Props = PropsWithChildren<StateProps & DispatchProps & RouteProps>;
function Profile(props: Props) {
    let [loading, setLoading] = useState(false);
    //组件加载后直接发起验证请求，查看此用户是否已经登录过了，如果没有登录则提示错误
    useEffect(() => {
        props.validate().catch((error: AxiosError) => message.error(error.message));
    }, []);
    const handleChange = (info: any) => {
        if (info.file.status === "uploading") {
            setLoading(true);
        } else if (info.file.status === "done") {
            let { success, data, message } = info.file.response;
            if (success) {
                setLoading(false);
                props.changeAvatar(data);
            } else {
                message.error(message);
            }
        }
    }
    let content; // 存放着要渲染的内容
    if (props.loginState == LOGIN_TYPES.UN_VALIDATE) {
        //如果未验证则内容为null
        content = null;
    } else if (props.loginState == LOGIN_TYPES.LOGINED) {
        const uploadButton = (
            <div>
                {loading ? <LoadingOutlined /> : <UploadOutlined />
                }
                <div className="ant-upload-text" > 上传</div >
            </div >
        );
        // 如果已经登录显示用户信息
        content = (
            <div className="user-info">
                <Descriptions title="当前登录用户">
                    <Descriptions.Item label="用户名">{props.user.username}</Descriptions.Item>
                    <Descriptions.Item label="邮箱">{props.user.email}</Descriptions.Item>
                    <Descriptions.Item label="头像">
                        <Upload
                            name="avatar"
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            action="http://39.98.141.106/user/uploadAvatar"
                            beforeUpload={beforeUpload}
                            data={{ userId: props.user._id }}
                            onChange={handleChange}
                        >
                            {props.user.avatar ? (
                                <img
                                    src={props.user.avatar}
                                    alt="avatar"
                                    style={{ width: "100%" }}
                                />
                            ) : (
                                    uploadButton
                                )}
                        </Upload>
                    </Descriptions.Item>
                </Descriptions>
                <Button type={"primary"} onClick={async () => {
                    await props.logout();
                    props.history.push("/login");
                }}>退出登录</Button>
            </div>
        );
    } else {
        //如果没有登录，则显示注册和登录按钮
        content = (
            <>
                <Alert type="warning" message="当前未登录" description="亲爱的用户你好，你当前尚未登录，请你选择注册或者登录" />
                <div style={{ textAlign: "center", padding: "50px" }}>
                    <Button type="dashed" onClick={() => props.history.push("/login")}>
                        登录
                    </Button>
                    <Button type="dashed" style={{ marginLeft: "50px" }} onClick={() => props.history.push("/register")}>注册</Button>
                </div>
            </>
        );
    }
    return (
        <section>
            <NavHeader history={props.history}>个人中心</NavHeader>
            {content}
        </section>
    )

}
const mapStateToProps = (initialState: CombinedState): ProFileState =>
    initialState.profile;
export default connect(mapStateToProps, actions)(Profile);
function beforeUpload(file: any) {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
        message.error("你只能上传JPG/PNG 文件!");
    }
    const isLessThan2M = file.size / 1024 / 1024 < 2;
    if (!isLessThan2M) {
        message.error("图片必须小于2MB!");
    }
    return isJpgOrPng && isLessThan2M;
}
